import json
import time
import requests
from flask import current_app
from app.models.decoration_request import DecorationRequest
from app import db

class CozeService:
    """Coze工作流服务类"""
    
    def __init__(self):
        self.personal_access_token = current_app.config['COZE_PERSONAL_ACCESS_TOKEN']
        self.workflow_id = current_app.config['COZE_WORKFLOW_ID']
        self.api_url = 'https://api.coze.cn/v1/workflow/run'
        
        if not all([self.personal_access_token, self.workflow_id]):
            raise ValueError("Coze配置不完整，请检查环境变量")
    
    def generate_decoration_plan(self, decoration_request):
        """
        调用Coze工作流生成装修方案
        
        Args:
            decoration_request: DecorationRequest对象
            
        Returns:
            工作流响应数据
        """
        try:
            # 更新请求状态为处理中
            decoration_request.status = 'processing'
            db.session.commit()
            
            # 准备请求头
            headers = {
                'Authorization': f'Bearer {self.personal_access_token}',
                'Content-Type': 'application/json',
                'Accept': 'application/json',
            }
            
            # 获取当前时间戳用于生成唯一标识
            timestamp = int(time.time())
            
            # 构建请求参数
            payload = {
                'workflow_id': self.workflow_id,
                'user': f"user_{timestamp}",
                'stream': False,
                'parameters': {
                    "USER_INPUT": decoration_request.decoration_plan,
                    "CONVERSATION_NAME": decoration_request.conversation_name,
                    "projectName": decoration_request.project_name,
                    "decorationStyle": decoration_request.decoration_style,
                    "roomType": decoration_request.room_type,
                    "floorPlanFile": decoration_request.floor_plan_url or '',
                    "decorationPlan": decoration_request.decoration_plan,
                    "budgetMin": str(decoration_request.budget_min),
                    "budgetMax": str(decoration_request.budget_max),
                }
            }
            
            # 发送请求
            response = requests.post(
                self.api_url,
                headers=headers,
                json=payload,
                timeout=120  # 增加超时时间
            )
            
            if response.status_code == 200:
                response_data = response.json()
                
                # 业务错误处理：Coze API 返回 200 但内部 code 非 0
                try:
                    inner_code = None
                    if isinstance(response_data, dict):
                        # 常见结构: { code, msg, data, ... }
                        inner_code = response_data.get('code')
                    # 另一些情况 data 内是字符串，里面也可能包含错误提示
                except Exception:
                    inner_code = None

                if inner_code not in (None, 0):
                    decoration_request.status = 'failed'
                    decoration_request.coze_response = json.dumps({
                        'error': response_data.get('msg') or 'Coze返回业务错误',
                        'detail': response_data
                    }, ensure_ascii=False)
                    db.session.commit()
                    return response_data

                # 正常成功
                decoration_request.coze_response = json.dumps(response_data, ensure_ascii=False)
                decoration_request.status = 'completed'

                # 提取图片URL
                image_urls = self._extract_image_urls(response_data)
                if image_urls:
                    decoration_request.generated_images = json.dumps(image_urls, ensure_ascii=False)

                db.session.commit()

                return response_data
            else:
                # 请求失败
                decoration_request.status = 'failed'
                decoration_request.coze_response = json.dumps({
                    'error': f'请求失败，状态码: {response.status_code}',
                    'response': response.text
                }, ensure_ascii=False)
                db.session.commit()
                
                raise Exception(f"Coze API请求失败，状态码: {response.status_code}, 响应: {response.text}")
                
        except requests.exceptions.Timeout:
            decoration_request.status = 'failed'
            decoration_request.coze_response = json.dumps({
                'error': '请求超时'
            }, ensure_ascii=False)
            db.session.commit()
            raise Exception("Coze API请求超时")
            
        except requests.exceptions.RequestException as e:
            decoration_request.status = 'failed'
            decoration_request.coze_response = json.dumps({
                'error': f'网络请求异常: {str(e)}'
            }, ensure_ascii=False)
            db.session.commit()
            raise Exception(f"网络请求异常: {str(e)}")
            
        except Exception as e:
            decoration_request.status = 'failed'
            decoration_request.coze_response = json.dumps({
                'error': f'处理异常: {str(e)}'
            }, ensure_ascii=False)
            db.session.commit()
            raise
    
    def _extract_image_urls(self, response_data):
        """
        从响应数据中提取图片URL
        
        Args:
            response_data: Coze API响应数据
            
        Returns:
            图片URL列表
        """
        image_urls = []
        
        try:
            # 从不同可能的字段中提取图片URL
            if 'image_urls' in response_data and isinstance(response_data['image_urls'], list):
                image_urls.extend(response_data['image_urls'])
            
            if 'image_url' in response_data and response_data['image_url']:
                image_urls.append(response_data['image_url'])
            
            # 从data字段中提取图片URL（Coze工作流的实际响应结构）
            if 'data' in response_data:
                data_content = response_data['data']
                if isinstance(data_content, str):
                    # 解析嵌套的JSON
                    try:
                        nested_data = json.loads(data_content)
                        content = nested_data.get('data', '')
                    except:
                        content = data_content
                else:
                    content = str(data_content)
                
                # 使用正则表达式提取图片URL
                import re
                urls = re.findall(r'https?://[^\s<>"]+', content)
                for url in urls:
                    if 'image' in url or 'tos-cn-i' in url or 'byteimg.com' in url:
                        image_urls.append(url)
            
            # 从输出文本中提取图片URL
            if 'output' in response_data:
                import re
                text = str(response_data['output'])
                urls = re.findall(r'https?://[^\s<>"]+', text)
                for url in urls:
                    if 'image' in url or 'tos-cn-i' in url or 'byteimg.com' in url:
                        image_urls.append(url)
            
            # 去重
            return list(set(image_urls))
            
        except Exception as e:
            print(f"提取图片URL时出错: {e}")
            return []
